/*
 * HttpResponseParser.cpp
 *
 *  Created on: 09.12.2012
 *      Author: zheka
 */

#include "HttpResponseParser.hpp"


#include <sstream>
#include <algorithm>
#include "util/ProxyException.hpp"
#include "util/StringUtils.hpp"
#include "http/HttpConstants.hpp"

HttpResponseParser::HttpResponseParser() :
		state(STATE_PARISING_HTTP_METHOD) {
}

bool HttpResponseParser::putLine(const std::string & line) {
	if (state == STATE_PARISING_HTTP_METHOD) {
		std::stringstream in(line);

		std::string httpVersion;
				if (!(in >> httpVersion)) {
					throw ProxyException(
							"[HttpRequestParser] Can't parse http version!");
				}

				if (std::find(HttpConstants::HTTP_VERSIONS.begin(), HttpConstants::HTTP_VERSIONS.end(), httpVersion) == HttpConstants::HTTP_VERSIONS.end()) {
					throw ProxyException(
							"[HttpRequestParser] Unsupported http version ("
									+ httpVersion + ")");
				}
				response.setHttpVersion(httpVersion);
		std::string responseCode;
		if (!(in >> responseCode)) {
			throw ProxyException(
					"[HttpRequestParser] Can't parse http response code!");
		}
		response.setResponseCode(responseCode);

		state = STATE_PARISING_HTTP_HEADERS;
		return true;
	} else if(state == STATE_PARISING_HTTP_HEADERS) {
		std::string s = StringUtils::trim(line);

			if (s.length() != 0) {
				int pos;
				if ((pos = s.find(HttpConstants::HTTP_HEADER_DELIMITER))
						== std::string::npos) {
					throw ProxyException(
							"[HttpRequestParser] Can't parse http header (" + s
									+ ")");
				}
				std::string key = s.substr(0, pos);
				std::string value = StringUtils::trim(
						s.substr(
								pos + HttpConstants::HTTP_HEADER_DELIMITER.length())); // skip ':'
				response.addHeader(key, value);

				return true;
			} else {
				state = STATE_PARISING_FINISHED;
				return false;
			}
	}

	return false;
}

HttpResponse HttpResponseParser::getHttpResponse() {
	return response;
}

